<?php
/*
*1.分析地址，然后路由至相应控制器
*/

//controller文件夹绝对地址
define('CONTROLLER_PATH','Controller/');

/*获取地址栏index.php后的字符串 
 * 每次转换是地址要是例如:index.php/reg_user
* return $uri
*/
$original_uri =  $_SERVER["REQUEST_URI"] ;
preg_match('/index.php\/(.*)/',$original_uri,$match_uri);
 
if(isset($match_uri[1])){
    $uri = $match_uri[1];
    
    //消除地址栏参数
    $uri = preg_replace('/\?(.)*/','',$uri);

    // 分开'/'
    $uri_array = explode('/',$uri);
    
    /*获取调用的函数名字,控制器名 ,文件所在地址*/
    
    /* uri_lv/uri_lv1/controller_name情况*/
    if(is_file(CONTROLLER_PATH.$uri.'.php')){
        $controller_path = CONTROLLER_PATH.$uri.'.php' ;
        $controller_name = $uri_array[count($uri_array)-1];
        $function_name = 'index';
    }
    /* uri_lv/uri_lv1/controller_name/function_name情况*/
    else{
        $function_name = $uri_array[count($uri_array)-1];
        $controller_name = $uri_array[count($uri_array)-2];
        $controller_path = CONTROLLER_PATH;
        for($i=0;$i<count($uri_array)-1;$i++){
            $controller_path .='/'.$uri_array[$i];
        }
        $controller_path .= '.php';
    }
    
}else{
    $controller_path = CONTROLLER_PATH.'index.php';
    $controller_name = "index";
    $function_name = "index";
}


/*
 * 2.调用相应的控制器文件，实例化类，调用类中的方法。
 */
try{
    echo "running $controller_path $controller_name";
    if(is_file(str_replace('index.php','',$controller_path)))
        require_once(str_replace('index.php','',$controller_path));
    else 
        require_once($controller_path);
        
    $controller = new $controller_name();
    $controller->$function_name();
    //throw
    
}catch(Exception $e){
}
?>